package cn.ciis.basic.auth;

import cn.ciis.basic.base.BaseCache;
import cn.ciis.basic.kit.J2CacheKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import java.util.List;
import java.util.Optional;

/**
 * 后台管理员授权业务
 *
 * @author 冉志林
 */
public class AdminAuthService {
    /**
     * 是否为超级管理员，role.id 值为 1 的为超级管理员
     */
    public boolean isSuperAdmin(int accountId) {

        List<Record> records = (List<Record>) J2CacheKit.get(BaseCache.AUTH_TIMEDCACHE,BaseCache.AUTH_TIMEDCACHE, x->{
            return Db.template("admin_auth.getSuperAdmin").find();
        },false).getValue();

        Optional<Record> optionalRecord = records.stream().filter(x -> x.getInt("accountId") == accountId).findFirst();

        return optionalRecord.isPresent();

    }

    /**
     * 当前账号是否拥有某些角色
     */
    public boolean hasRole(int accountId, String[] roleNameArray) {
        if (roleNameArray == null || roleNameArray.length == 0) {
            return false;
        }

        Kv data = Kv.by("accountId", accountId).set("roleNameArray", roleNameArray);
        Integer ret = Db.template("admin_auth.hasRole", data).queryInt();
        return ret != null;
    }

    /**
     * 是否拥有具体某个权限
     */
    public boolean hasPermission(int accountId, String actionKey) {
        if (StrKit.isBlank(actionKey)) {
            return false;
        }

        Integer ret = Db.template("admin_auth.hasPermission", actionKey, accountId).queryInt();
        return ret != null;
    }
}
